<template>
  <!-- 挂载容器 -->
  <div ref="react">{{errorMessage}}</div>
</template>

<script>
import Vue from 'vue';
import Component from 'vue-class-component';

let React = null;

@Component({
  props: {
    // 组件地址
    url: {
      type: String,
      required: true
    },
    // 传递给组件的初始数据
    propsData: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    url: {
      handler: function(url, oldUrl) {
        if (url) {
          this.importComponent();
        }
      }
    }
  }
})
export default class ReactComponent extends Vue {
  errorMessage = '';

  // 载入React组件
  async importComponent() {
    if (!React) {
      console.log('加载 react 运行库');
      React = await import('react');
    }
    try {
      const m = await import(`@components/v2/${this.url}`);
      React.render(
        React.createElement(m.default, { 
          $container: this,
          $vue: Vue,
          $router: this.$router,
          ...this.propsData || {} 
        }),
        this.$refs.react
      );
    } catch (e) {
      this.errorMessage = '加载失败';
      throw new Error(e);
    }
  }

  mounted() {
    this.importComponent();
  }
}
</script>
